package com.ysqcould.common.utils;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedHashMap;

/**
 * 高德地图转换工具类
 * @author jcd
 */
public class GdMapUtils {
    /**
     * 在高地地图申请的key
     */
    private static final String GOULD_KEY = "f597d9f28d7ed13886a2a6262395756c";

    /**
     * 地址转换为经纬度
     * @param address 地址
     * @return 经纬度
     */
    public static String getLonLat(String address) {
        // 返回输入地址address的经纬度信息, 格式是 经度,纬度
        String queryUrl = "http://restapi.amap.com/v3/geocode/geo?key="+GOULD_KEY+"&address=" + address;
        // 高德接品返回的是JSON格式的字符串
        String queryResult = getResponse(queryUrl);
        JSONObject job = JSONObject.parseObject(queryResult);
        JSONObject jobJSON = JSONObject
                .parseObject(job.get("geocodes").toString().substring(1, job.get("geocodes").toString().length() - 1));
        JSONObject json=new JSONObject(new LinkedHashMap<>());
        if (ObjectUtil.isNotEmpty(jobJSON)){
            json.put("name",jobJSON.getString("formatted_address"));
            json.put("coord",jobJSON.getString("location"));
        }
        return json.toString();
    }
    /**
     * 发送请求
     * @param serverUrl 请求地址
     */
    public static String getResponse(String serverUrl) {
        // 用JAVA发起http请求，并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }
}
